import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {path: '/',redirect:'/login'},
  {path: '/login',name: 'login',component: ()=>import('../views/login')},
  {path:'/home',name:'home',component:()=>import('../views/Home'),redirect:'/reports',
   children:[
    {path:'/reports',name:'reports',component:()=>import('../views/report/report')},
    // 二级菜单路由,因为是显示在 home 组件的 el-main中，所以应该为home的子路由
    {path:'/users',name:'users',component:()=>import('../views/User/user')},
    {path:'/rights',name:'rights',component:()=>import('../views/Power/rights')},
    {path:'/roles',name:'roles',component:()=>import('../views/Power/roles')},
    {path:'/categories',name:'cate',component:()=>import('../views/Goods/cate')},
    {path:'/goods',name:'goods',component:()=>import('../views/Goods/list')},
    {path:'/goods/add',name:'add',component:()=>import('../views/Goods/goods')},
    {path:'/params',name:'params',component:()=>import('../views/Goods/params')},
    {path:'/orders',name:'order',component:()=>import('../views/Order/order')}
   ]
  },
]

const router = new VueRouter({
  routes
})

// 防止重复跳转
const VueRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(to) {
  return VueRouterPush.call(this, to).catch(err => err)
}
// 全局路由守卫
router.beforeEach((to,from,next)=>{
  // 只要访问登录页，都可以放行
  if(to.path ==='/login') return next()
  const token = window.sessionStorage.getItem('token')
  // 如果没有token，将回到登录页
  if(!token) return next('/login')
  // 否则放行
  next()
})
export default router
